/**
 * Connection.java
 * Copyright (C) 2011 Yuanyan<yuanyan.cao@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * For information on how to redistribute this software under
 * the terms of a license other than GNU General Public License
 * contact yuanyan.cao@gmail.com
 */
package edu.rabbit.kernel.sql;

import java.io.File;


import edu.rabbit.Database;
import edu.rabbit.DbErrorCode;
import edu.rabbit.DbException;
import edu.rabbit.schema.ISchema;
import edu.rabbit.table.RunnableWithLock;

/**
 * @author Yuanyan<yanyan.cao@gmail.com>
 * 
 */
public class Connection {

    private Database db;

    protected Connection(String fileName) throws DbException {
        db = Database.open(new File(fileName), false);
    }

    public static Connection open(String fileName) throws DbException {
        return new Connection(fileName);
    }

    public PreparedStatement prepare(String sql) throws DbException {
        if (sql == null || sql.trim().length() == 0) {
            throw new DbException(DbErrorCode.ERROR, "SQL statement is empty");
        }
        return new PreparedStatement(db, sql);
    }

    public void exec(final String sql, final ExecCallback callback) throws DbException {
        db.runWithLock(new RunnableWithLock() {

            public Object runWithLock(Database db) throws DbException {
                PreparedStatement stmt = prepare(sql);
                try {
                    while (stmt.step()) {
                        if (callback != null) {
                            callback.processRow(stmt);
                        }
                    }
                } finally {
                    stmt.close();
                }
                return null;
            }
        });
    }

    public void close() throws DbException {
        db.close();
    }

    public ISchema getSchema(String databaseName) throws DbException {
        return db.getSchema();
    }
}
